import { useImperativeHandle, forwardRef, useState, useEffect, useRef, MouseEvent } from 'react';
import { cloneDeep } from 'lodash';
import moment from 'moment';
import { Checkbox, Modal, Typography } from 'antd';
import { InbizIcon, getEditor } from '@inbiz/utils';
import FilterTab from './FilterTab';
import Paginations from './Pagenations';
import Avatar from '../../Avatar';
import TableInfo from '../../TableInfo';
import ProcessLogModal from '../../ProcessLogModal';
import NoData from '../../NoData';
import Spin from '../../Spin';
import ProcessIcon from '../../ProcessIcon';
import { TextWidget, getMessage } from '@inbiz/react';
import { afterOperation, getLogInfo, getFormData } from '../../../utils';
import { goto, processState, goPopupDetail, goDrawerDetail, getSummary, getProcessInfoAfterCustomClickItem } from '../../../../commonUtils';
import { removeDraft } from '../../../service';
import type { processStructure } from '../../../types';
import '../style.less';

const dataFormat = 'YYYY-MM-DD HH:mm:ss';

const { Paragraph } = Typography;
const ProcessCenterView = forwardRef((props: any, ref) => {
  const {
    tabsArr,
    userInfo,
    choosedTabKey,
    showTabTitle,
    rangeConfig,
    processGroup,
    openMode,
    openPopUpHeight,
    openPopUpWidth,
    drawerWidth,
    searchBarRef,
    ifQuickApproval,
    getGroup,
    getMyToDo,
    getApplying,
    getDraft,
    getToMe,
    getMyApply,
    getHaveDone,
    getClassification,
    configEvents,
    customClickItem,
  } = props;

  // 流程列表loading
  const [loading, setLoading] = useState(false);
  // 数据展示方式
  const [showTableView, setShowTableView] = useState(sessionStorage.getItem('showTableInfo') ? sessionStorage.getItem('showTableInfo') == '1' ? true : false : false);
  // 流程列表数据
  const [infoList, setInfoList] = useState<any[]>([]);
  // 流程列表分页
  const [pageData, setPageData] = useState({
    pageIndex: 1,
    pageSize: 50,
    total: 0,
  });
  // 已选项
  const [choosedItems, setChoosedItems] = useState<processStructure[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  // 流程日志
  const [logVisible, $logVisible] = useState(false);
  const [logInfo, $logInfo] = useState({
    instanceId: '',
    processId: '',
  });

  const filterRef = useRef<any>();
  const isEditor = getEditor();

  // 接口返回数据后做处理
  const standardData = (res: { details: { rows: any[]; currPage: any; pageSize: any; total: any; }; }, key: string) => {
    if (res && res?.details && res?.details?.rows?.length > 0) {
      let arr: any[] = [];
      switch (key) {
        case '2':
          arr = res.details.rows.map((item: { taskState: any; summary: string; }) => ({
            ...item,
            taskState: item.taskState ?? '0',
            checked: false,
            summary:
              item.summary && item.summary.startsWith('<')
                ? getSummary(item.summary)
                : item.summary,
          }));
          setInfoList((pre: any) => {
            let checkedArr = pre?.map((item: any) => {
              if (item?.checked == true) {
                return item?.taskId;
              }
            });
            if (checkedArr && checkedArr?.length > 0) {
              arr = arr?.map((item2: any) => {
                if (checkedArr?.includes(item2?.taskId)) {
                  return {
                    ...item2,
                    checked: true,
                  };
                } else {
                  return item2;
                }
              });
            }
            return arr;
          });
          break;
        case '3':
        case '6':
          arr = res.details.rows.map((item: { taskState: any; processState: any; processStartTime: any; summary: string; }) => ({
            ...item,
            taskState: item.taskState || item.processState || 0,
            taskCreateTime: item.processStartTime,
            summary:
              item.summary && item.summary.startsWith('<')
                ? getSummary(item.summary)
                : item.summary,
          }));
          setInfoList(arr);
          break;
        case '4':
          arr = res.details.rows.map((item: { taskState: any; processState: any; creationTime: any; summary: string; }) => ({
            ...item,
            taskState: item.taskState || item.processState || 0,
            taskCreateTime: item.creationTime,
            summary:
              item.summary && item.summary.startsWith('<')
                ? getSummary(item.summary)
                : item.summary,
          }));
          setInfoList(arr);
          break;
        case '5':
          arr = res.details.rows.map((item: { taskState: string; starterName: any; taskStartTime: any; summary: string; }) => ({
            ...item,
            taskState:
              item.taskState == '170' || item.taskState == '180'
                ? item.taskState ?? '0'
                : '150',
            initiatorName: item.starterName,
            taskCreateTime: item.taskStartTime,
            summary:
              item.summary && item.summary.startsWith('<')
                ? getSummary(item.summary)
                : item.summary,
          }));
          setInfoList(arr);
          break;
        case '7':
          arr = res.details.rows.map((item: { taskState: any; processState: any; summary: string; }) => ({
            ...item,
            taskState: item.taskState || item.processState || 0,
            summary:
              item.summary && item.summary.startsWith('<')
                ? getSummary(item.summary)
                : item.summary,
          }));
          setInfoList(arr);
          break;
        case '8':
          arr = res.details.rows.map((item: { taskState: any; processState: any; processCreateTime: any; summary: string; }) => ({
            ...item,
            taskState: item.taskState || item.processState || 0,
            taskCreateTime: item.processCreateTime,
            summary:
              item.summary && item.summary.startsWith('<')
                ? getSummary(item.summary)
                : item.summary,
          }));
          setInfoList(arr);
          break;
        default:
          break;
      }
      setPageData({
        pageIndex: res.details.currPage,
        pageSize: res.details.pageSize,
        total: res.details.total,
      });
    } else {
      setInfoList([]);
      setPageData({
        pageIndex: 1,
        pageSize: pageData.pageSize,
        total: 0,
      });
    }
  }

  // 获取列表数据
  const getList = async (
    pageIndex: number,
    pageSize: number,
    key: string,
    value: string,
    searchCondition: any,
    callback?: Function,
  ) => {
    const dptKey =
      rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
        ? ''
        : processGroup?.groupGuid ?? '';
    let result: any;
    let params: any;
    switch (key) {
      case '2':
        params = getFormData(
          userInfo,
          pageIndex,
          pageSize,
          rangeConfig,
          dptKey,
          value,
          searchCondition,
        );
        result = await getMyToDo(params)
        break;
      case '3':
        params = getFormData(
          userInfo,
          pageIndex,
          pageSize,
          rangeConfig,
          dptKey,
          value,
          searchCondition,
        );
        params['isunderApplication'] = true;
        result = await getApplying(params);
        break;
      case '4':
        params = getFormData(
          userInfo,
          pageIndex,
          pageSize,
          rangeConfig,
          dptKey,
          value,
          searchCondition,
          true,
        );
        result = await getDraft(params)
        break;
      case '5':
        params = getFormData(
          userInfo,
          pageIndex,
          pageSize,
          rangeConfig,
          dptKey,
          value,
          searchCondition,
        );
        result = await getToMe(params);
        break;
      case '6':
        params = getFormData(
          userInfo,
          pageIndex,
          pageSize,
          rangeConfig,
          dptKey,
          value,
          searchCondition,
        );
        params['isunderApplication'] = false;
        result = await getMyApply(params);
        break;
      case '7':
        params = getFormData(
          userInfo,
          pageIndex,
          pageSize,
          rangeConfig,
          dptKey,
          value,
          searchCondition,
        );
        result = await getHaveDone(params);
        break;
      case '8':
        params = getFormData(
          userInfo,
          pageIndex,
          pageSize,
          rangeConfig,
          dptKey,
          value,
          searchCondition,
        );
        result = await getClassification(params);
        break;
      default:
        break;
    }
    standardData(result, key);
    if (callback) {
      callback();
    }
  };

  // 获取首屏数据
  const getInitData = async () => {
    setLoading(true);
    await getList(pageData?.pageIndex, pageData.pageSize, choosedTabKey, '', {
      processGroupName: '',
      processDefId: '',
      date: '',
      status: '',
    });
    setLoading(false);
  }

  useEffect(() => {
    getInitData();
  }, []);

  // 选中 取消任务
  const checkList = (item: processStructure, boolean: boolean) => {
    let _infoList = infoList?.map((item1: any) => {
      if (item1.taskId == item.taskId) {
        return {
          ...item1,
          checked: boolean
        }
      } else {
        return item1;
      }
    });
    let _choosedItems = _infoList?.filter((item1: any) => item1?.checked);
    let _infoListKey = _choosedItems?.map((item2: any) => item2?.taskId);
    setSelectedRowKeys(_infoListKey);
    setChoosedItems(_choosedItems);
    setInfoList(_infoList);
  };

  // table格式选中行
  const changeRows = (tselectedRowKeys: any, tselectedRows: any[] | ((prevState: processStructure[]) => processStructure[])) => {
    setSelectedRowKeys(tselectedRowKeys);
    setChoosedItems(tselectedRows);
    let sectedArr = tselectedRows?.map((item: any) => item?.taskId);
    setInfoList((pre: any) => {
      if (sectedArr && sectedArr?.length > 0) {
        pre = pre?.map((item2: any) => {
          if (sectedArr?.includes(item2?.taskId)) {
            return {
              ...item2,
              checked: true,
            };
          } else {
            return item2;
          }
        });
        return pre;
      } else {
        return pre;
      }
    });
  };

  // 删除草稿
  const delDraft = (e: MouseEvent<HTMLDivElement, MouseEvent>, item: processStructure) => {
    if (isEditor) {
      return;
    }
    e.stopPropagation();
    Modal.confirm({
      title: getMessage('processCenter.AreYouSureYouWantToDeleteThisProcessDraft'),
      content: '',
      okText: getMessage('global.sure'),
      cancelText: getMessage('global.cancel'),
      onOk: () => {
        const params = {
          drafID: item.draftsId,
        };
        removeDraft(params).then((res) => {
          afterOperation(res, async () => {
            setLoading(true);
            await getList(1, pageData.pageSize, choosedTabKey, '', {
              processGroupName: '',
              processDefId: '',
              date: '',
              status: '',
            });
            setLoading(false);
          });
        });
      },
    });
  };

  const goView = (e: MouseEvent<Element, globalThis.MouseEvent> | undefined, item: { taskId: any; processInstanceId: any; draftsId: any; taskState: any; }) => {
    let _callback = async () => {
      setLoading(true);
      await getList(
        infoList?.length == 1 && pageData.pageIndex != 1
          ? pageData.pageIndex - 1
          : pageData.pageIndex,
        pageData.pageSize,
        '2',
        searchBarRef?.current?.searchText,
        filterRef?.current?.searchCondition,
        () => { },
      );
      setLoading(false);
      filterRef?.current?.searchApplyList();
    };
    if (openMode == 'newPage') {
      goto(
        {
          taskIds: item.taskId,
          processInstanceId: item.processInstanceId,
          inItiateApplication: false,
          drafID: item.draftsId,
          taskState: item.taskState,
          siteType: 0,
        },
        '2',
        'web',
        e,
        '',
        _callback,
        setLoading,
      );
    } else if (openMode == 'popUp') {
      goPopupDetail(
        item,
        '2',
        openPopUpHeight,
        openPopUpWidth,
        setLoading,
        _callback,
      );
    } else if (openMode == 'rightDrawer') {
      goDrawerDetail(item, '2', drawerWidth, setLoading, _callback);
    }
  };

  const goGetLogInfo = (e: MouseEvent<Element, globalThis.MouseEvent>, item: { taskId: any; processInstanceId: any; taskState: any; }) => {
    getLogInfo(
      e,
      {
        taskIds: item.taskId,
        processInstanceId: item.processInstanceId,
        inItiateApplication: false,
        taskState: item.taskState,
        siteType: 3,
      },
      $logVisible,
      $logInfo,
      setLoading,
    )
  };

  const afterQuickApproval = () => {
    setChoosedItems([]);
    setSelectedRowKeys([]);
    let _infoList = infoList?.map((item) => {
      return {
        ...item,
        checked: false,
      }
    });
    setInfoList(_infoList);
  };

  // 向外暴露的方法
  useImperativeHandle(ref, () => ({
    searchInfo: async (text: string) => {
      setLoading(true);
      filterRef?.current?.resetSearchCondition();
      setPageData({
        pageIndex: 1,
        pageSize: pageData.pageSize,
        total: 0,
      });
      await getList(
        1,
        pageData.pageSize,
        choosedTabKey,
        text || searchBarRef?.current?.searchText,
        {
          processGroupName: '',
          processDefId: '',
          date: '',
          status: '',
        },
      )
      setLoading(false);
    },
  }));

  // 分页组件
  const pageComponent = (
    <div className="pagination">
      {infoList.length > 0 && (
        <Paginations
          pageData={pageData}
          onChange={async (page: number, pageSize: number) => {
            if (isEditor) {
              return;
            }
            setSelectedRowKeys([]);
            setChoosedItems([]);
            setLoading(true);
            await getList(
              page,
              pageSize,
              choosedTabKey,
              searchBarRef?.current?.searchText,
              filterRef?.current?.searchCondition,
            );
            setLoading(false);
          }}
        />
      )}
    </div>
  )

  const filterProps = {
    tabsArr,
    choosedTabKey,
    choosedItems,
    setChoosedItems,
    $showTableInfo: setShowTableView,
    showTableInfo: showTableView,
    list: infoList,
    isEditor,
    userInfo,
    $selectedRowKeys: setSelectedRowKeys,
    $list: setInfoList,
    getList,
    pageData,
    searchBarRef,
    afterOperation,
    rangeConfig,
    processGroup,
    setLoading,
    goView,
    goGetLogInfo,
    afterQuickApproval,
    ifQuickApproval,
    getGroup,
    configEvents,
  };

  return (
    <div className="cardContainer">
      <FilterTab {...filterProps} ref={filterRef} />
      <Spin spinning={loading}>
        {
          infoList?.length > 0
            ?
            showTableView
              ?
              <>
                <div className="tableInfo">
                  <TableInfo
                    rowSelection={
                      choosedTabKey == '2'
                        ? {
                          selectedRowKeys,
                          onChange: changeRows,
                          type: 'checkbox',
                          columnWidth: 55,
                        }
                        : {
                          selectedRowKeys,
                          onChange: changeRows,
                          type: 'radio',
                          renderCell: () => '',
                        }
                    }
                    showTabTitle={showTabTitle}
                    choosedItem={choosedItems}
                    choosedTabKey={choosedTabKey}
                    delDraft={delDraft}
                    getList={getList}
                    infoList={infoList}
                    pageData={pageData}
                    searchText={searchBarRef?.current?.searchText}
                    condition={filterRef?.current?.searchCondition}
                    searchApplyList={filterRef?.current?.searchApplyList}
                    openMode={openMode}
                    openPopUpHeight={openPopUpHeight}
                    openPopUpWidth={openPopUpWidth}
                    drawerWidth={drawerWidth}
                    setLoading={setLoading}
                    customClickItem={customClickItem}
                  />
                </div>
                {pageComponent}
              </>
              :
              <>
                <div className="cardInfo">
                  <div className="cardInfoContainer">
                    {infoList?.map((item: processStructure, index: number) => {
                      return (
                        <div
                          className={`cardItem${item.checked ? ' checkedItem' : ''}`}
                          key={(item.taskId || item.processInstanceId) + choosedTabKey || ''}
                          style={{
                            height:
                              choosedTabKey !== '3' && choosedTabKey !== '4' && choosedTabKey !== '6'
                                ? 325
                                : 280,
                          }}
                          onClick={async (e) => {
                            if (customClickItem) {
                              const params = choosedTabKey == '4' ? {
                                processDefinitionId: item.procDefId,
                                businessKey: item.businessKey,
                                drafID: item.draftsId,
                                inItiateApplication: true,
                                taskState: item.taskState,
                                siteType: 0,
                              } : {
                                taskIds: item.taskId,
                                processInstanceId: item.processInstanceId,
                                inItiateApplication: false,
                                drafID: item.draftsId,
                                taskState: item.taskState,
                                siteType: 0,
                              };
                              const result = await getProcessInfoAfterCustomClickItem(params);
                              customClickItem({ event: e, processItem: item, requestItem: result });
                              return;
                            }
                            let _callback =
                              choosedTabKey == '4'
                                ? async () => {
                                  setLoading(true);
                                  await getList(
                                    infoList?.length == 1 && pageData.pageIndex != 1
                                      ? pageData.pageIndex - 1
                                      : pageData.pageIndex,
                                    pageData.pageSize,
                                    choosedTabKey,
                                    searchBarRef?.current?.searchText,
                                    filterRef?.current?.searchCondition,
                                  );
                                  setLoading(false);
                                  filterRef?.current?.searchApplyList();
                                }
                                : async () => {
                                  setLoading(true);
                                  await getList(
                                    infoList?.length == 1 && pageData.pageIndex != 1
                                      ? pageData.pageIndex - 1
                                      : pageData.pageIndex,
                                    pageData.pageSize,
                                    choosedTabKey,
                                    searchBarRef?.current?.searchText,
                                    filterRef?.current?.searchCondition,
                                    () => {
                                      if (choosedTabKey == '2' && infoList?.length >= 10) {
                                        setTimeout(() => {
                                          let _wrapper =
                                            document.getElementsByClassName('cardInfo')[0];
                                          if (_wrapper) {
                                            let _scrollBody =
                                              _wrapper.getElementsByClassName('cardInfoContainer')[0];
                                            let _item =
                                              _scrollBody.getElementsByClassName('cardItem')[
                                              infoList?.length > (index || 0) ? index : infoList?.length
                                              ];
                                            _item.scrollIntoView();
                                          }
                                        }, 0);
                                      }
                                    },
                                  );
                                  setLoading(false);
                                  filterRef?.current?.searchApplyList();
                                };
                            if (openMode == 'newPage') {
                              if (choosedTabKey == '4') {
                                goto(
                                  {
                                    processDefinitionId: item.procDefId,
                                    businessKey: item.businessKey,
                                    drafID: item.draftsId,
                                    inItiateApplication: true,
                                    taskState: item.taskState,
                                    siteType: 0,
                                  },
                                  choosedTabKey,
                                  'web',
                                  e,
                                  '',
                                  _callback,
                                  setLoading,
                                );
                              } else {
                                goto(
                                  {
                                    taskIds: item.taskId,
                                    processInstanceId: item.processInstanceId,
                                    inItiateApplication: false,
                                    drafID: item.draftsId,
                                    taskState: item.taskState,
                                    siteType: 0,
                                  },
                                  choosedTabKey,
                                  'web',
                                  e,
                                  '',
                                  _callback,
                                  setLoading,
                                );
                              }
                            } else if (openMode == 'popUp') {
                              goPopupDetail(
                                item,
                                choosedTabKey,
                                openPopUpHeight,
                                openPopUpWidth,
                                setLoading,
                                _callback,
                              );
                            } else if (openMode == 'rightDrawer') {
                              goDrawerDetail(item, choosedTabKey, drawerWidth, setLoading, _callback);
                            }
                          }}
                        >
                          {choosedTabKey !== '4' && (
                            <div className="header">
                              <div
                                style={{ display: 'flex', flex: 1 }}
                                onClick={(e) => {
                                  e.stopPropagation();
                                }}
                              >
                                {choosedTabKey == '2' && (
                                  <div onClick={(e) => e.stopPropagation()}>
                                    <Checkbox
                                      className="checkbox"
                                      onChange={(e) => {
                                        e.stopPropagation();
                                        checkList(item, e.target.checked);
                                      }}
                                      checked={item?.checked}
                                    />
                                  </div>
                                )}
                                <TextWidget>processCenter.instanceNumber</TextWidget>:{' '}
                                {item.processInstanceId || ''}
                              </div>
                              <div style={{ display: 'flex' }}>
                                {(item?.urgeState === 0 || item?.urgeState === 250) &&
                                  (choosedTabKey == '2' || choosedTabKey == '3' || choosedTabKey == '6') && (
                                    <InbizIcon
                                      style={{
                                        fontSize: 18,
                                        marginLeft: 15,
                                      }}
                                      type="icon-a-zu2259"
                                    />
                                  )}
                                <div
                                  style={{
                                    width: 52,
                                    height: 24,
                                    color: processState[item.taskState].stateFontColor || '',
                                    background: processState[item.taskState].stateBgColor || '',
                                    lineHeight: '24px',
                                    borderRadius: '4px',
                                    textAlign: 'center',
                                  }}
                                >
                                  <TextWidget>{processState[item.taskState].stateName}</TextWidget>
                                </div>
                              </div>
                            </div>
                          )}
                          <div
                            className="content"
                            style={{
                              height:
                                choosedTabKey !== '3' && choosedTabKey !== '4' && choosedTabKey !== '6'
                                  ? 230
                                  : choosedTabKey !== '4'
                                    ? 185
                                    : 205,
                            }}
                          >
                            {choosedTabKey != '3' && choosedTabKey != '4' && choosedTabKey != '6' && (
                              <div style={{ textAlign: 'left' }}>
                                <Avatar userId={item.userId || ''} />
                                <span title={item.initiatorName} style={{ color: '#707070' }}>
                                  {item.initiatorName && item.initiatorName.length > 10
                                    ? `${item.initiatorName.slice(0, 10)}...`
                                    : item.initiatorName || ''}
                                </span>
                              </div>
                            )}
                            <div
                              style={{
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'space-between',
                              }}
                            >
                              <div
                                style={{
                                  display: 'flex',
                                  alignItems: 'center',
                                }}
                              >
                                <ProcessIcon
                                  processIconInfo={
                                    item?.proLcon ? item?.proLcon?.trim() : 'font_family'
                                  }
                                />
                                <span style={{ color: '#707070' }} title={item.processName}>
                                  {item.processName.length > 10
                                    ? item.processName.slice(0, 9) + '...'
                                    : item.processName ?? ''}
                                </span>
                              </div>
                              {choosedTabKey == '4' && (
                                <div className="deleteDraft" onClick={(e) => delDraft(e, item)}>
                                  <InbizIcon
                                    style={{ fontSize: 18, color: '#afafaf' }}
                                    type="icon-ic-delete"
                                  />
                                </div>
                              )}
                            </div>
                            {(choosedTabKey == '2' ||
                              choosedTabKey == '5' ||
                              choosedTabKey == '7' ||
                              choosedTabKey == '8') && (
                                <div
                                  style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'space-between',
                                  }}
                                >
                                  <div
                                    style={{
                                      display: 'flex',
                                      alignItems: 'center',
                                    }}
                                  >
                                    <InbizIcon
                                      style={{
                                        fontSize: 25,
                                        marginRight: 15,
                                      }}
                                      type={'icon-woderenwu'}
                                    />
                                    <span style={{ color: '#707070' }}>{item.stepName || ''}</span>
                                  </div>
                                </div>
                              )}
                            <div className="summary" title={item.summary}>
                              <div className="summaryTitle">
                                <TextWidget>processCenter.summary</TextWidget>:{' '}
                              </div>
                              <Paragraph ellipsis={{ rows: 4 }}>{item.summary || ''}</Paragraph>
                            </div>
                          </div>
                          <div className="footer">
                            <div
                              onClick={(e) => {
                                goGetLogInfo(e, item);
                              }}
                              style={{
                                visibility: choosedTabKey == '4' ? 'hidden' : 'visible',
                              }}
                            >
                              <InbizIcon
                                type="icon-process-liuchengrizhi"
                                style={{ fontSize: 20, color: '#666' }}
                              />
                            </div>
                            <div>{moment(item.taskCreateTime).format(dataFormat)}</div>
                          </div>
                        </div>
                      );
                    })}
                    {[1, 2, 3, 4, 5, 6].map((ele) => {
                      return <div key={ele} className="card-rest" />;
                    })}
                  </div>
                </div>
                {pageComponent}
              </>
            :
            !loading && <NoData />
        }
      </Spin>
      {
        logVisible
        &&
        <ProcessLogModal visible={logVisible} $visible={$logVisible} logInfo={logInfo} />
      }
    </div>
  );
});

export default ProcessCenterView;
